import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisZset {
    // 清空数据库
    public static void flushAll(Jedis jedis) {
        jedis.flushAll();
    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");

        try (Jedis jedis = jedisPool.getResource()){
            flushAll(jedis);
            test1(jedis);
        }
    }

    // zadd, zrange, zrangeWithScores, zcard, zrem, zscore
    private static void test1(Jedis jedis) {
        // jedis.zadd("key1", 10, "llt");
        Map<String, Double> map = new HashMap<>();
        map.put("llt", 18.0);
        map.put("lpy", 19.0);
        map.put("oop", 20.0);

        jedis.zadd("key1", map);

        // 获取范围内的 member
        System.out.println("key1 中的 member: " + jedis.zrange("key1", 0, -1));

        // 获取个数
        System.out.println("key1 中的元素个数: " + jedis.zcard("key1"));

        // 删除指定的 member
        System.out.println("删除的个数: " + jedis.zrem("key1", "lpy"));

        // 获取范围内的 member, score
        System.out.println("key1 中的 member 和分数: " + jedis.zrangeWithScores("key1", 0, -1));

        // 获取某一个 member
        List<Tuple> memberWithScore = jedis.zrangeWithScores("key1", 0, -1);
        String member = memberWithScore.get(0).getElement();
        double score = memberWithScore.get(0).getScore();
        System.out.println("0位置 member: " + member+ ", score: " + score);

        // 根据 member 获取 score
        System.out.println("llt 对应的 score 为: " + jedis.zscore("key1", "llt"));
    }

}
